import type { AnyObject } from "antd/es/_util/type";
import { useCallback, useEffect, useState } from "react";

type Props = {
  AMap: typeof AMap | undefined | null,
  map: AMap.Map | undefined |null
}

const provinceFill = 'rgba(20, 120, 230,0.5)';
const otherCountry = 'rgb(17,34,69)'



const useInitCountry = ({ AMap, map }: Props) => {

  const [code, setCode] = useState<number>()


  // 初始化国家图层并绑定点击事件
  const initDisCountry = useCallback(() => {
    if (!AMap || !map) return
    setCode(510000)

    const disWorld = new AMap.DistrictLayer.World({
      zIndex: 13,
      styles: {
        'fill': function (_: AnyObject) {
          if (_.SOC !== 'CHN') {
            return otherCountry
          }
        },
        "nation-stroke": otherCountry, // 国界颜色
        "province-stroke": otherCountry, // 省界颜色
        'coastline-stroke':otherCountry

      }
    });
    const disProvince = new AMap.DistrictLayer.Country({
      zIndex: 12,
      depth: 0,
      styles: {
        'fill': function (e: AnyObject) {
          if (e.adcode == 510000) {
            // updateInfo(props);
            return provinceFill;
          }

        },

      }
    });

    disWorld.setMap(map);
    disProvince.setMap(map);
    map.on('click', function (ev: AMap.MapsEvent) {

      const px = ev.pixel;
      // 拾取所在位置的行政区
      const props = disProvince.getDistrictByContainerPos(px);

      if (props) {
        const adcode = props.adcode;
        setCode(adcode)
        if (adcode) {
          // 重置行政区样式
          disProvince.setStyles({
            'fill': function (props: AnyObject) {
              if (props.adcode == adcode) {
                return provinceFill
              }
            },

          });
        }
      }
    });


  }, [AMap, map])





  useEffect(() => {
    initDisCountry()
  }, [initDisCountry])



  return {
    provinceCode: code
  }
}

export default useInitCountry